import datetime

from flask import Flask
from flask_mail import Mail

from config import baseConfig
from flask.json import JSONEncoder
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy


class CustomJSONEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime("%Y-%m-%d %H:%M:%S")
        elif isinstance(o, datetime.date):
            return o.strftime("%Y-%m-%d")
        else:
            return JSONEncoder.default(self, o)


moment = Moment()
db = SQLAlchemy()
mail = Mail()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(baseConfig[config_name])
    baseConfig[config_name].init_app(app)
    app.json_encoder = CustomJSONEncoder
    moment.init_app(app)
    db.init_app(app)
    mail.init_app(app)

    from app.user import user as user_blueprint

    # 注册蓝图
    app.register_blueprint(user_blueprint, url_prefix='/user')

    return app






